<template>
	<BasicModal @register="registerModalInner" :title="getTitle" @ok="handleSubmit">
		<BasicForm @register="registerForm"></BasicForm>
	</BasicModal>
</template>

<script setup lang="ts">
import { BasicModal, BasicForm } from '#/components';
import { useForm } from '#/hooks';
import { useModalInner } from '#/Modal';
import type { FormSchema } from '#/types';
import { addOrEditRole } from '@/api/sys/role';
import { useMessage } from '@/hooks/web/useMessage';
import { computed, ref, unref } from 'vue';

const formSchema: FormSchema[] = [
	{
		field: 'roleName',
		label: '角色名称',
		component: 'Input',
		required: true,
	},
	{
		field: 'roleCode',
		label: '角色编码',
		component: 'Input',
		required: true,
	},
	{
		field: 'remark',
		label: '备注',
		component: 'InputTextArea',
	},
];

const isUpdate = ref(true);
const roleId = ref();

const { createMessage } = useMessage();

const [registerModalInner, { closeModal }] = useModalInner(data => {
	resetFields();
	isUpdate.value = !!data?.isUpdate;

	if (unref(isUpdate)) {
		roleId.value = data.record.roleId;
		setFieldsValue({ ...data.record });
	}
});

const [registerForm, { setFieldsValue, validate, resetFields }] = useForm({
	labelWidth: 100,
	schemas: formSchema,
	showActionButtonGroup: false,
	baseRowStyle: {
		'justify-content': 'space-around',
	},
	baseColProps: {
		span: 20,
	},
});

const getTitle = computed(() => (unref(isUpdate) ? '编辑角色' : '新增角色'));

const emit = defineEmits(['success', 'register']);
async function handleSubmit() {
	try {
		const values = await validate();
		unref(isUpdate) && (values.roleId = roleId.value);
		await addOrEditRole(isUpdate.value, values);
		closeModal();
		emit('success');
	} catch (_err) {
		createMessage.error('操作失败');
	}
}
</script>
<style lang="less" scoped></style>
